#!/bin/bash

################################################################################
#使用前准备
# 1. 远程机器统一创建xxx OS用户，密码统一，并修改/etc/sudoers文件，
#    将xxx用户加入sudo；
# 2. 远程机器统一在数据库中创建xxx@localhost用户，密码统一
#    create user xxx@localhost identified by 'xxx';
#    grant usage,select on *.* to xxx@localhost;
#    grant execute on sys.* to xxx@localhost;
#	 update mysql.user set Process_priv='Y' where user='xxx' and host='localhost';
#	 flush privileges;
################################################################################
#变量定义

#待检查主机列表
HOST_LIST=("10.10.10.11" \
"10.10.10.12")

#待检查主机sshd端口列表
SSHPORT_LIST=(22 \
22)

#待检查主机mysql端口列表
MYPORT_LIST=(3306 \
3306)

#待检查主机socket路径列表
MYSOCK_LIST=("/var/lib/mysql/mysql.sock" \
"/var/lib/mysql/mysql.sock")

PASSWD="xxx"
MYPWD="xxx"
SCRIPTS_NAME="/checklog/check.sh"
GATHER_DIR="/checklog/report$(date '+%s')";mkdir -p ${GATHER_DIR}

CNT=$((${#HOST_LIST[*]}-1))
CNT=$(eval "echo {0..$CNT}")

SLEEP_SECS=900

################################################################################
#传输脚本
for idx in $CNT
do
/usr/bin/expect <<EOF
spawn scp -P${SSHPORT_LIST[idx]} ${SCRIPTS_NAME} xxx@${HOST_LIST[idx]}:/tmp/remote_sh.sh
expect {
"password:" { send "${PASSWD}\r" }
}
expect eof
exit
EOF
done

################################################################################
#执行脚本

for idx in $CNT
do
echo "nohup /tmp/remote_sh.sh xxx ${MYPWD} ${MYPORT_LIST[idx]} ${MYSOCK_LIST[idx]}"
/usr/bin/expect <<EOF
spawn ssh -p${SSHPORT_LIST[idx]} xxx@${HOST_LIST[idx]}
expect {
"password:" { send "${PASSWD}\r" }
}
expect "]# "
send "echo 'xxx\r' | sudo -i -S\r"
send "sudo -i\r"
send "rm -f /checklog/report*.html\r"
send "nohup /tmp/remote_sh.sh xxx ${MYPWD} ${MYPORT_LIST[idx]} ${MYSOCK_LIST[idx]} > /tmp/mysqlCheckRun.log 2>&1 ; rm -f /tmp/remote_sh.sh &\r"
send "exit\r"
expect eof
exit

EOF

done

################################################################################
#收集执行报告
sleep ${SLEEP_SECS}

for idx in $CNT
do
/usr/bin/expect <<EOF
spawn scp -P${SSHPORT_LIST[idx]} -r xxx@${HOST_LIST[idx]}:/home/xxx/report*.html ${GATHER_DIR}/.
expect {
"password:" { send "${PASSWD}\r" }
}
expect eof
exit
EOF
done

if [ -d ${GATHER_DIR} ]
then
	tar -cvzf ${GATHER_DIR}.tar.gz ${GATHER_DIR}/*;
        sz ${GATHER_DIR}.tar.gz
fi